<template>
    <NSpace>
        <UITable ref="tableRef" :row-key="(row: ModelExtend) => row.key || row.id" size="small"
            :style="{ height: `${tableHeight}px` }" flex-height :columns="columns" :data="modelsComputed || []"
            :bordered="true" />
        <NSpace>
            <UIButton :loading="loading" type='info' @click="getModel">获取模型</UIButton>
            <UIButton :loading="loading" type='primary' @click="createModel">
                添加模型
            </UIButton>
        </NSpace>
    </NSpace>
</template>

<script setup lang="tsx">
import { NInput, NSwitch, NCard, NSpace } from 'naive-ui';
import UIButton from '@/components/UI/Button/index.vue'
import UITable from '@/components/UI/Table/index.vue'
import { TableColumns } from 'naive-ui/es/data-table/src/interface';
import { storeToRefs } from 'pinia';
const tableHeight = 300;
const searchValue = ref({
    id: '',
    name: '',
    active: '2'
})
const tableRef = useTemplateRef<InstanceType<typeof UITable>>('tableRef')
const columns: TableColumns<ModelExtend> = [
    {
        title: '模型ID',
        key: 'id',
        ellipsis: {
            tooltip: true
        },
        render(row) {
            return row.key ? h(NInput, {
                size: 'small',
                placeholder: '请输入模型ID',
                value: row.id,
                onUpdateValue(value) {
                    setModelState(row.id, "id", value)
                }
            }) : row.id.replace('models/', '')
        },
        filter: true,
        renderFilterIcon: () => <UIButton text iconName='Search'></UIButton>,
        renderFilterMenu: () =>
            <NCard class='p-2'>
                <NInput value={searchValue.value.id} onUpdate:value={(value) => {
                    searchValue.value.id = value;
                }} placeholder={'请输入要筛选的模型ID'} />
            </NCard>
    },
    {
        title: '模型名称',
        key: 'name',
        ellipsis: {
            tooltip: true
        },
        render(row) {
            return h(NInput, {
                size: 'small',
                placeholder: '请输入模型名称',
                value: row.name,
                onUpdateValue(value) {
                    setModelState(row.id, "name", value)
                }
            })
        },
        filter: true,
        renderFilterIcon: () => <UIButton text iconName='Search'></UIButton>,
        renderFilterMenu: () =>
            <NCard class='p-2'>
                <NInput value={searchValue.value.name} onUpdate:value={(value) => {
                    searchValue.value.name = value;
                }} placeholder={'请输入要筛选的模型名称'} />
            </NCard>
    },
    {
        title: "状态",
        key: 'active',
        render(row) {
            return (
                <div class="flex items-center gap-4">
                    <NSwitch size="small" value={row.active} onUpdate:value={(value) => {
                        setModelState(row.id, 'active', value)
                    }} />
                    {row.key ? <UIButton onClick={() => {
                        const filteredModels = getNowProviderSetting()?.MODELS.filter((model) => model.key !== row.key) || []
                        setNowProviderSetting("MODELS", filteredModels)
                    }} iconName='Delete' type='error' text size='tiny'></UIButton> : null}
                </div>
            )
        },
        width: 100,
        defaultFilterOptionValues: ['2'],
        filterOptions: [
            {
                label: '全部',
                value: '2'
            },
            {
                label: '是',
                value: '1'
            },
            {
                label: '否',
                value: '0'
            },
        ],
        filterMultiple: false,
        filter(value, row) {
            if (value === '2') {
                return true;
            }
            return Boolean(row.active) === Boolean(+value);
        }
    },
]
const { setNowProviderSetting, getNowProviderSetting, addModel } = settingsStore()
const createModel = async () => {
    addModel(getNowProviderSetting()!.PROVIDES)
    await nextTick()
    tableRef.value!.scrollTo({ top: modelsComputed.value.length * 45 })
}
const { settings, getNowProviderSettingIndex } = storeToRefs(settingsStore())

const modelsComputed = computed(() => {
    return getNowProviderSetting()?.MODELS.filter(
        item => item.id?.indexOf(searchValue.value.id) !== -1
            && item.name?.indexOf(searchValue.value.name) !== -1) || []
})
const setModelState = <K extends keyof ModelExtend>(ModelId: string, key: K, value: ModelExtend[K]) => {
    const index = getNowProviderSetting()?.MODELS.findIndex((model) => model.id === ModelId)
    if (index !== -1) {
        settings.value.aiSetting.value[getNowProviderSettingIndex.value].MODELS[index!][key] = value
    }
}
const loading = ref(false)
const getModel = async () => {
    try {
        loading.value = true;
        const provider = getNowProviderSetting()!;
        const { data } = await openAiService().getModel(provider.API_URL, provider.API_KEY);
        setNowProviderSetting("MODELS", data.map(e => ({ ...e, provider: provider.PROVIDES } as ModelExtend)));
    } catch (error) {
        console.error(error);
    } finally {
        loading.value = false
    }
}

</script>
